/**
 * 
 */
package ikeuilib;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;



/**
 * @author ikechan
 *
 */
public class TableFontEditor extends AbstractCellEditor implements TableCellEditor, ActionListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Font currentFont;
	private JButton button;
	private JFontDialog dialog;
	private JTable currentTable;
	protected static final String EDIT = "edit";

	public TableFontEditor() {
		button = new JButton();
		button.setActionCommand(EDIT);
		button.addActionListener(this);
		button.setBorderPainted(false);
		dialog =new JFontDialog();
		dialog.setAlwaysOnTop(true);
	}
	
	public Component getTableCellEditorComponent(JTable arg0, Object arg1,
			boolean arg2, int arg3, int arg4) {
		currentFont = (Font)arg1;
		currentTable=arg0;
		return button;
	}

	public Object getCellEditorValue() {
		return currentFont;
	}

	public void actionPerformed(ActionEvent arg0) {
		button.setFont(currentFont);
		Font f=dialog.getFont(button);
		if(f!=null){
			currentFont=f;
			currentTable.setValueAt(currentFont, currentTable.getSelectedRow(),
					currentTable.getSelectedColumn());
			currentTable.removeEditor();
		}else{
			currentTable.removeEditor();
		}
	}

	public static void main(String[] args){
		JFrame f=new JFrame();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JTable tb=new JTable();
		final DefaultTableModel model=new DefaultTableModel(){
			private static final long serialVersionUID = 1L;
			@Override
			public boolean isCellEditable(int arg0, int arg1) {
				return (arg1==1);
			}
			@Override
			public Class<?> getColumnClass(int arg0) {
				if(arg0==1){
					return Font.class;
				}else{
					return super.getColumnClass(arg0);
				}
			}
			
		};
		model.setColumnCount(2);
		model.setRowCount(1);
		model.setColumnIdentifiers(new String[]{"Name","Value"});
		tb.setDefaultEditor(Font.class, new TableFontEditor());
		tb.setDefaultRenderer(Font.class, new TableFontRenderer(true));
		model.setValueAt("Font", 0, 0);
		model.setValueAt(tb.getFont(), 0, 1);
		tb.setModel(model);
		f.getContentPane().setLayout(new BorderLayout());
		f.getContentPane().add(new JScrollPane(tb),BorderLayout.CENTER);
		f.setTitle("Test");
		f.setSize(300,200);
		f.setLocationRelativeTo(null);
		f.setVisible(true);
	}
}
